import os
from pathlib import Path


def read_output_dir():
    env_path = Path(__file__).resolve().parents[1] / 'luogu-snap' / '.env'
    if env_path.exists():
        for line in env_path.read_text(encoding='utf-8').splitlines():
            if line.startswith('OUTPUT_DIR='):
                return Path(line.split('=', 1)[1].strip())
    return Path.cwd() / 'output'


def build_gallery(out_dir: Path):
    out_dir.mkdir(parents=True, exist_ok=True)
    files = sorted([f.name for f in out_dir.glob('*.png')])
    items = '\n'.join([f'<div class="item"><img src="{name}" /><div class="name">{name}</div></div>' for name in files])
    html = f'''<!doctype html><html><head><meta charset="utf-8"/><style>body{{font-family:Consolas,monospace}} .grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:12px;padding:16px}} .item img{{width:100%;height:auto;border:1px solid #ddd;border-radius:6px}} .name{{font-size:12px;color:#666;margin-top:4px}}</style></head><body><div class="grid">{items}</div></body></html>'''
    (out_dir / 'index.html').write_text(html, encoding='utf-8')
    print('Gallery written to', out_dir / 'index.html')


if __name__ == '__main__':
    out_dir = read_output_dir()
    build_gallery(out_dir)

